<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="130px">
            <el-form-item label="课程学期" prop="term">
                <el-select v-model="queryParams.term" placeholder="请选择课程学期" clearable style="width: 200px">
                    <el-option
                            v-for="dict in course_term"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="课程名称" prop="name">
                <el-input
                        v-model="queryParams.name"
                        placeholder="请输入课程名称"
                        clearable
                        @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item label="老师选择" prop="userId">
                <el-select v-model="queryParams.userId" placeholder="请选择老师" style="width: 200px" >
                    <el-option
                            v-for="teacher in teachers"
                            :key="teacher.userId"
                            :label="teacher.userName"
                            :value="teacher.userId"

                    />
                </el-select>
            </el-form-item>

            <el-form-item style="margin-left: 45px">
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <el-row :gutter="10" class="mb8">
            <el-link type="primary">选课信息</el-link>
        </el-row>


        <div style="border: #006eb9 solid 1px;border-radius: 10px;">
            <el-table v-loading="loading" :data="studentCourseList" @selection-change="handleSelectionChange">
                <!--      <el-table-column type="selection" width="55" align="center" />-->
                <!--        id，但是不展示-->
                <div style="display: none">
                    <el-table-column label="id" align="center" prop="id" />
                </div>
                <el-table-column label="课程名称" align="center" prop="name" />
                <el-table-column label="课程学期" align="center" prop="term">
                    <template #default="scope">
                        <dict-tag :options="course_term" :value="scope.row.term"/>
                    </template>
                </el-table-column>
                <!--        userId-->
                <div style="display: none">
                    <el-table-column label="userId" align="center" prop="userId" />
                </div>
                <el-table-column label="老师" align="center" prop="teacher.userName" />
                <el-table-column label="当前人数 / 最大人数" align="center">
                    <template #default="{ row }">
                        {{ row.nownum }}/{{ row.maxnum }}
                    </template>
                </el-table-column>

                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" >
                    <template #default="scope" >
                        <el-button
                                v-if="!scope.row.selected"
                                link
                                type="primary"
                                icon="Edit"
                                @click="handleUpdate(scope.row)"
                                v-hasPermi="['studentCourse:studentCourse:edit']"
                                :disabled="scope.row.selected"
                        >选课</el-button>
                        <el-button link
                                   type="secondary"
                                   disabled v-else><el-icon><CircleCheck /></el-icon>&nbsp;已选</el-button>
                        <el-button
                                v-if="scope.row.selected"
                                link
                                type="primary"
                                icon="ArrowLeft"
                                @click="handledeUpdate(scope.row)"
                                v-hasPermi="['studentCourse:studentCourse:edit']">
                            退课
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

        </div>
        <pagination
                v-show="total>0"
                :total="total"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                @pagination="getList()"
        />
    </div>
</template>

<script setup name="StudentCourse">
    import {listTeacher, listStudentCourse, getStudentCourse, delStudentCourse, addStudentCourse, updateStudentCourse,deUpdateStudentCourse } from "@/api/studentCourse/studentCourse";
    // import { listTeacher } from "@/api/course/course"
    import {onMounted, ref} from "vue";
    import { ElMessage,ElMessageBox } from 'element-plus';
    const { proxy } = getCurrentInstance();
    const { course_arrangement, course_term, user_week } = proxy.useDict('course_arrangement', 'course_term', 'user_week');

    const studentCourseList = ref([]);
    const open = ref(false);
    const loading = ref(false);
    const showSearch = ref(true);
    const ids = ref([]);
    const single = ref(true);
    const multiple = ref(true);
    const total = ref(0);
    const title = ref("");


    const teachers = ref([]);

    onMounted(() => {
        loadTeachers();
    });

    // 查询所有老师
    const loadTeachers = async () => {
        try {
            const response = await listTeacher();
            teachers.value = response.data || []; // 假设response.data是包含老师列表的数组
        } catch (error) {
            console.error('Error fetching teachers:', error);
        }
    };


    const data = reactive({
        form: {
            userId:localStorage.getItem('userId'),
        },
        queryParams: {
            pageNum: 1,
            pageSize: 50,
            name: null,
            term: null,
            arrangement: null,
            coursedesc: null,
            classroom: null,
            maxnum: null,
            nownum:null,
            imgs: null,
            starttime: null,
            endtime: null,
            courseweek: null,
            userId: null,
            teacher: {
                userId: null,
                userName: null
            }
        },
        rules: {
            name: [
                { required: true, message: "课程名称不能为空", trigger: "blur" }
            ],
        }
    });

    const { queryParams, form, rules } = toRefs(data);

    /** 查询我要选课列表 */
    const getList = () => {
        listStudentCourse(queryParams.value).then(response => {
            const currentMonth = new Date().getMonth() + 1; // 获取当前月份，注意JavaScript中月份是从0开始的
            const termToShow = currentMonth <= 6 ? '第一学期' : '第二学期'; // 根据月份决定显示哪个学期
            studentCourseList.value = response.rows
                .filter(row => row.term === termToShow) // 筛选出要显示的学期的课程
                .map(row => ({
                    ...row,
                    selected: selectedStatuses.value.get(row.id) || false,
                }));
            total.value = response.total;
        });
    };
    // 取消按钮
    function cancel() {
        open.value = false;
        reset();
    }

    // 表单重置
    function reset() {
        form.value = {
            id: null,
            name: null,
            hours: null,
            credits: null,
            term: null,
            arrangement: null,
            coursedesc: null,
            classroom: null,
            maxnum: null,
            nownum:null,
            imgs: null,
            starttime: null,
            endtime: null,
            courseweek: null,
            userId: null,
            teacher: {
                userId: null,
                userName: null
            }
        };
        proxy.resetForm("studentCourseRef");
    }

    /** 搜索按钮操作 */
    function handleQuery() {
        queryParams.value.pageNum = 1;
        getList();
    }

    /** 重置按钮操作 */
    function resetQuery() {
        proxy.resetForm("queryRef");
        handleQuery();
    }

    // 多选框选中数据
    function handleSelectionChange(selection) {
        ids.value = selection.map(item => item.id);
        single.value = selection.length != 1;
        multiple.value = !selection.length;
    }




    const selectedStatuses = ref(new Map());
    /** 选课按钮操作 */
    const handleUpdate = async (row) => {

        // 设置selected状态为true，即使后续失败也不再允许选课
        selectedStatuses.value.set(row.id, true);

        const payload = {
            //必须要传递,学生编号,要往student_course插入userId
            userId: localStorage.getItem('userId'),
            id: row.id,
            maxnum: row.maxnum,
            nownum: row.nownum,
        };

        const result = await updateStudentCourse(payload);
        if (result === -1) {
            ElMessage.error('选课失败，您已选过该课程！');
        } else {
            ElMessage.success('选课成功');
            await getList();
        }

    };

    /** 退课按钮操作 */
    const handledeUpdate = async (row) => {
        try {
            // 显示确认对话框
            const confirmResult = await ElMessageBox.confirm(
                '确定要退课吗？',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }
            );

            if (confirmResult === 'confirm') {
                // 用户点击了确定按钮，准备退课请求的payload
                const payload = {
                    userId: localStorage.getItem('userId'),
                    id: row.id,
                    // 如果需要，可以添加更多字段
                };

                // 发送退课请求
                const result = await deUpdateStudentCourse(payload);

                if (result) {
                    ElMessage.success('退课成功');
                    // 重置selected状态
                    selectedStatuses.value.set(row.id, false);
                    // 重新加载列表以反映最新的选课状态
                    await getList();
                } else {
                    ElMessage.warning('取消退课');
                }
            } else {
                // 用户点击了取消按钮，不做任何操作
                ElMessage.info('已取消退课');
            }
        } catch (error) {
            ElMessage.info('已取消退课');
            console.error(error);
        }
    };

    /** 提交按钮 */
    function submitForm() {
        proxy.$refs["studentCourseRef"].validate(valid => {
            if (valid) {
                if (form.value.id != null) {
                    updateStudentCourse(form.value).then(response => {
                        proxy.$modal.msgSuccess("选课成功");
                        // open.value = false;
                        getList();
                    });
                } else {
                    addStudentCourse(form.value).then(response => {
                        proxy.$modal.msgSuccess("新增成功");
                        open.value = false;
                        getList();
                    });
                }
            }
        });
    }




    getList();
</script>
<style scoped>
    .el-link {
        font-size: 26px;
        margin: 0 auto;
        text-align: center;
        margin-bottom: 8px;
    }
    .el-link .el-icon--right.el-icon {
        vertical-align: text-bottom;

    }
    .el-table{
        width: 95%;
        border-radius: 10px;
        margin: 40px;
    }
</style>
